package com.jinzhu.common.httpclient;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;


/**
 * @author jz
 * md5 加密斑马zeek签名授权
 */
@Service
@Slf4j
public class ZeekAuthSignature {


    @Getter
    @Setter
    @Value("${zeek.appid}")
    private Integer APP_ID;

    @Getter
    @Setter
    @Value("${zeek.appsecret}")
    private String APP_SECRET;

    @Getter
    @Setter
    @Value("${zeek.url}")
    private String APP_URL;

    /**
     * 加密签名
     *
     * @param obj         传入的父级参数
     * @param excludeJson 要排除的json字段
     * @return
     * @throws Exception
     */
//    public Auth authSignatrue(Obj obj, String... excludeJson) throws Exception {
//        //按照zeek文档格式排除非数字和字符的json字段并且根据json首字段排序
//
//        log.info("排除非字符和非数字\n{}\n\n", Arrays.toString(excludeJson));
//        String s = ExcludeJsonProperties.excludeProperties(obj, excludeJson);
//        log.info("排除非字符和非数字然后按照json首字母排序的json结果\n{}\n\n", s);
//        //根据zeek文档将吧APPID和APPSECRET拼接到remarks字段后进行MD5加密
//        StringBuffer signature = new StringBuffer();
//        //计算时间戳
//        signature.append(HttpJsonUtil.jsonToGet(s)).append("&").append(APP_ID)
//                .append("&")
//                .append(APP_SECRET)
//                .append("&")
//                .append("1528793155");
//        log.info("排序后的json转换成=&拼接进行MD5加密:\n{}", signature);
//        //将MD5签名放入auth的signature字段中
//        return new Auth(APP_ID, getSecondTimestamp(new Date()), MD5Util.md5(signature.toString()));
//    }

    /**
     * 获取精确到秒的时间戳
     *
     * @return
     */
    public int getSecondTimestamp(Date date) {
        if (null == date) {
            return 0;
        }
        String timestamp = String.valueOf(date.getTime());
        int length = timestamp.length();
        if (length > 3) {
            return Integer.valueOf(timestamp.substring(0, length - 3));
        } else {
            return 0;
        }
    }

    /**
     * 第三方请求回调结果
     *
     * @param obj
     * @param url
     * @return
     * @throws IOException
     */
    public JSONObject result(String context,Object obj, String url) throws IOException {
        //转换成json字符串并且序列化美观度打印以及排序 格式化--PrettyFormat 排除为null--WriteMapNullValue 字母排序--MapSortField
        String json = JSONObject.toJSONString(obj, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.MapSortField);
        log.info("最终打印传给第三方Json:\n{}\n", json);
        HttpRequestConfig config = HttpRequestConfig
                .create()
                .url(this.getAPP_URL() + url)
                .httpEntityType(HttpEntityType.ENTITY_JSON)
                .json(json);
        String responseText = HttpClientUtils.post(config).getResponseText();
        log.info("第三方响应结果\n{}\n",responseText);
        String subResponseText = responseText.substring(responseText.indexOf("{"));
        JSONObject result=JSONObject.parseObject(subResponseText);
        log.info("第三方{}响应结果\n{}\n",context,JSONObject.toJSONString(result, SerializerFeature.PrettyFormat));
        return result;

    }
}
